package com.modules.upms.controller;

import com.common.enums.CommonEnum;
import com.common.util.R;
import com.common.web.BaseController;
import com.modules.upms.common.util.TreeUtil;
import com.modules.upms.entity.SysDept;
import com.modules.upms.entity.SysDict;
import com.modules.upms.entity.SysMenu;
import com.modules.upms.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单
 */
@RestController
@RequestMapping(value = "/sys/menu")
public class SysMenuController extends BaseController {
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 通过角色名称查询用户菜单
     *
     * @param role 角色名称
     * @return 菜单列表
     */
    @GetMapping(value = "/findMenuByRole/{role}")
    public R<List<SysMenu>> findMenuByRole(@PathVariable String role) {
        return R.success(sysMenuService.findMenuByRoleName(role));
    }

    /**
     * 返回当前用户的树形菜单集合
     *
     * @return 当前用户的树形菜单
     */
    @GetMapping(value = "/userMenu")
    public R<List<SysMenu>> userMenu() {
        // 获取符合条件得菜单
        List<SysMenu> menuList = sysMenuService.findMenuByUserId(getUserId());

        List<SysMenu> menuTreeList = menuList.stream().filter(vo -> CommonEnum.MENU.getCode()
                .equals(vo.getType()))
                .sorted(Comparator.comparingInt(SysMenu::getSort))
                .collect(Collectors.toList());
        return R.success(TreeUtil.bulid(menuTreeList, CommonEnum.TREE_ROOT_NODE.getCode()));
    }

    /**
     * 返回树形菜单集合
     *
     * @return 树形菜单
     */
    @GetMapping(value = "/listTree")
    public R<List<SysMenu>> getTree(SysMenu query) {
        return R.success(TreeUtil.bulid(sysMenuService.getList(query), CommonEnum.TREE_ROOT_NODE.getCode()));
    }


    /**
     * 新增菜单
     *
     * @param sysMenu 菜单信息
     * @return success/false
     */
    @PostMapping(value = "/save")
    public R<Boolean> save(@RequestBody SysMenu sysMenu) {
        return new R<>(sysMenuService.saveOrUpdate(sysMenu));
    }

    /**
     * 更新排序
     * @param list
     * @return
     */
    @PostMapping(value = "/updateSorts")
    public R<SysDept> updateSorts(@RequestBody List<SysMenu> list){
        sysMenuService.updateSorts(list);
        return R.success();
    }

    /**
     * 更新状态
     * @param sysMenu
     * @return
     */
    @PostMapping(value = "/updateStatus")
    public R<SysDept> updateStatus(@RequestBody SysMenu sysMenu){
        sysMenuService.updateStatus(sysMenu);
        return R.success();
    }


    /**
     * 删除菜单
     *
     * @param id 菜单ID
     * @return success/false
     * TODO  级联删除下级节点
     */
    @DeleteMapping(value = "/{id}")
    public R<Boolean> deleteMenuById(@PathVariable Integer id) {
        return new R<>(sysMenuService.deleteById(id));
    }

}
